<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>登录</title>
  <link rel="stylesheet" href="css/auth.css">

</head>

<body>
  <div class="container">
    <h2>登录</h2>
    <form id="login-form">
      <input type="text" id="login-username" placeholder="用户名" required />
      <input type="password" id="login-password" placeholder="密码" required />
      <button type="submit">登录</button>
    </form>
    <p>没有账号？<a href="register.html">注册</a></p>
  </div>

  <script>
    document.getElementById('login-form').addEventListener('submit', async function (e) {
      e.preventDefault();

      const username = document.getElementById('login-username').value;
      const password = document.getElementById('login-password').value;

      try {
        const response = await fetch('http://localhost:3000/api/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ username, password })
        });

        const data = await response.json();
        if (response.ok) {
          // 登录成功，保存 JWT 到本地存储
          localStorage.setItem('token', data.token);
          alert('登录成功！');
          window.location.href = './index.html'; // 登录成功后跳转到首页或其他受保护的页面
        } else {
          alert('登录失败: ' + data.message);
        }
      } catch (error) {
        alert('登录请求失败: ' + error.message);
      }
    });
  </script>
</body>

</html>